<script setup>
import {onMounted, ref, watch} from "vue";
import * as echarts from "echarts";

const props = defineProps({
  title: {
    type: String,
    default: '图表标题'
  },
  showMore: {
    type: Boolean,
    default: false
  },
  options: {
    type: Object,
    default: () => {
      return {};
    }
  }
});
// 定义随机的DOM ID，这样可以避免多图表渲染的问题
const chartsDomRef = ref(Math.random());
// 组件挂载后初始化图表
onMounted(() => {
  initCharts();
});
// 监听数据变化，重新初始化图表
watch(() => props.options, () => {
  initCharts();
}, {deep: true});
// 监听窗口变化
window.addEventListener('resize', () => {
  console.log('resize')
  initCharts();
});
const initCharts = () => {
  // 判断DOM对象是否已经存在
  let myChartRef = echarts.getInstanceByDom(document.getElementById(chartsDomRef.value));
  if (myChartRef) {
    // 先销毁之前的DOM实例
    myChartRef.dispose();
  }
  // 获取DOM对象，初始化echarts实例
  myChartRef = echarts.init(document.getElementById(chartsDomRef.value));
  // 使用刚指定的配置项和数据显示图表。
  myChartRef.setOption({
    ...props.options
  });
};
const emits = defineEmits(['more']);
const more = () => {
  emits('more');
};
</script>

<template>
  <div class="v-charts-container">
    <div class="v-charts-header">
      <span>{{ props.title }}</span>
      <span v-if="showMore" @click="more">查看更多</span>
    </div>
    <div :id="chartsDomRef" class="v-charts-body"></div>
  </div>
</template>

<style scoped lang="scss">
.v-charts-container {
  width: 100%;
  height: 100%;
  margin: 10px 0;
  background-color: #fff;
  
  .v-charts-header {
    padding: 10px;
    box-sizing: border-box;
    height: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    > span:nth-child(1) {
      font-size: 16px;
      font-weight: bold;
    }
    
    > span:nth-child(2) {
      font-size: 14px;
      color: #185EFF;
      cursor: pointer;
    }
    
    > span:nth-child(2):hover {
      text-decoration: underline;
    }
  }
  
  .v-charts-body {
    padding: 10px;
    box-sizing: border-box;
    width: 100%;
    height: calc(100% - 60px);
  }
}

.v-charts-container:hover {
  box-shadow: 0 0 10px #ccc;
}
</style>